package cn.cuilan.service;

import cn.cuilan.cache.AbstractRedisService;
import cn.cuilan.repository.UserRepository;
import cn.cuilan.entity.User;
import cn.cuilan.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户服务层实现类
 *
 * @author zhang.yan
 */
@Service
public class UserService extends AbstractRedisService<User> {

    /**
     * redis缓存key
     */
    private final static String USER_KEY = "USER_KEY";

    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public String getRedisKey() {
        return USER_KEY;
    }

    public User getById(long id) {
        User user = this.get(id + "");
        if (user == null) {
            user = userRepository.findOne(id);
            this.put(id + "", user, 600);
        }
        return user;
    }

    /**
     * 登陆，判断手机号或邮箱
     *
     * @param userName 手机号或邮箱
     * @return 返回数据库中的用户对象
     */
    public User login(String userName) {
        // 判断用户名是手机号还是邮箱
        if (userName.contains(GlobalConstant.LOGIN_MAIL_SUBSTRING)) {
            return userRepository.findUserByLoginMail(userName);
        } else {
            return userRepository.findUserByLoginPhone(userName);
        }
    }
}
